import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Form,
  Layout,
  DatePicker,
  Input,
  Select,
  Button,
  Table,
  Modal,
  Pagination,
  message,
  Checkbox,
} from 'antd';
import {
  DEFAULT_PAGE_SIZE,
  DEFAULT_VALID_STATE,
  CONST_PERMISSION_CODE_DUTY_NOTE_SHOW_ALL,
} from '@/constants';
import styles from './index.less';
import _ from 'lodash';

import Edit from './edit';
import Export from './export';

const { Content } = Layout;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { confirm } = Modal;
const CheckboxGroup = Checkbox.Group;

const CONDITIONS = [
  { label: '时间', field: 'filterTime', type: 'dateRange' },
  // { label: '类型', field: 'filterType', type: 'select', placeholder: '请选选择类型' }
];

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'dutyNotesNew';
    const { global } = props;
    const { currentUnit = {} } = global;

    this.state = {
      plainOptions: [],
      checkedList: [],
      indeterminate: true,
      checkAll: false,
      noticeVisible: false,
      noticeType: -1,
      selectType: '防台防汛',
      selectStatement: 1,
      currentUnitName: currentUnit.unit_name || '',
      query: {
        // state: DEFAULT_VALID_STATE,
        // unit_id: {
        //   id: currentUnit.id || -1
        // },
        unitId: currentUnit.id || -1,
      },
      chooseArray: [],
    };
  }

  componentDidMount() {
    this.queryData(1, DEFAULT_PAGE_SIZE);
  }

  componentDidUpdate(preProps, preState) {
    if (!_.isEqual(preProps.modular.callTypeData, this.props.modular.callTypeData)) {
      const plainOptions = this.props.modular.callTypeData?.map(item => item.unit);
      this.setState({ plainOptions });
    }
    if (preState.noticeType != this.state.noticeType) {
      if (this.state.noticeType === 0) {
        const plainOptions = this.props.modular.callTypeData?.map(item => item.unit);
        this.setState({ plainOptions });
      }
      // if(this.state.noticeType === 1) {
      //   console.log(this.props)
      //   const plainOptions = this.props.unit.data?.map(item => item.unit_name)
      //   this.setState({plainOptions})
      // }
    }
  }

  // componentWillUnmount() {
  //   this.props.dispatch({ type: `${this.modularName}/clear` })
  // }

  appendBtnClick = () => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '新增值守保障', editData: {} },
    });
  };

  editBtnClick = record => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑值守保障', editData: record },
    });
  };

  exportBtnClick = record => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visibleExport: '数据导出' },
    });
  };

  // 查询按钮
  queryList() {
    const { dispatch, form } = this.props;
    const { query, currentUnitName } = this.state;

    form.validateFields({ force: true }, (err, values) => {
      const remember = {};
      remember.unitId = query.unitId;
      if (values.filterTime || values.filterType) {
        let filterTime = values.filterTime;
        let filterType = values.filterType;
        if (values.filterTime) {
          remember.startTime = moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00');
          remember.endTime = moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59');
        }
        if (values.filterType) {
          remember.rememberType = filterType;
        }
        dispatch({
          type: `${this.modularName}/queryData`,
          payload: {
            current: 1,
            pageSize: 10,
            eventCreateUser: currentUnitName,
            eventStartTime: moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00'),
            eventEndTime: moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59'),
          },
        });
      } else {
        dispatch({
          type: `${this.modularName}/queryData`,
          payload: {
            current: 1,
            pageSize: 10,
            eventCreateUser: currentUnitName,
            // ...query,
          },
        });
      }
    });
  }

  queryData = (current, pageSize) => {
    const { query, currentUnitName } = this.state;
    const { dispatch, global } = this.props;
    const { userPermissions = [] } = global;
    const remember = {};

    if (!userPermissions || !userPermissions.includes(CONST_PERMISSION_CODE_DUTY_NOTE_SHOW_ALL)) {
      remember.unitId = query.unitId;
    }

    dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        current,
        pageSize,
        eventCreateUser: currentUnitName,
      },
    });
  };

  onChange = (current, pageSize) => {
    const { query = {}, currentUnitName } = this.state;
    debugger;
    const { dispatch, global, form } = this.props;
    const { userPermissions = [] } = global;

    form.validateFields({ force: true }, (err, values) => {
      const remember = {};

      if (!userPermissions || !userPermissions.includes(CONST_PERMISSION_CODE_DUTY_NOTE_SHOW_ALL)) {
        remember.unitId = query.unitId;
      }
      if (values.filterTime || values.filterType) {
        let filterTime = values.filterTime;
        let filterType = values.filterType;
        if (values.filterTime) {
          remember.startTime = moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00');
          remember.endTime = moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59');
        }
        if (values.filterType) {
          remember.rememberType = filterType;
        }
        dispatch({
          type: `${this.modularName}/queryData`,
          payload: {
            current,
            pageSize,
            eventCreateUser: currentUnitName,
            eventStartTime: moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00'),
            eventEndTime: moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59'),
          },
        });
      } else {
        dispatch({
          type: `${this.modularName}/queryData`,
          payload: {
            current,
            pageSize,
            eventCreateUser: currentUnitName,
          },
        });
      }
    });
  };

  onShowSizeChange = (current, pageSize) => {
    this.onChange(1, pageSize);
  };

  // 删除
  stopBtnClick = record => {
    confirm({
      title: '是否确定删除该条数据?',
      onOk: () => {
        const { dispatch, form, modular } = this.props;
        const { query, chooseArray, currentUnitName } = this.state;
        const { current, pageSize } = modular;

        form.validateFields({ force: true }, (err, values) => {
          let aa = [];
          if (chooseArray && chooseArray.length > 0) {
            aa = chooseArray;
          } else {
            aa = [];
            aa.push(record.id);
          }

          if (values.filterTime) {
            let filterTime = values.filterTime;

            dispatch({
              type: `${this.modularName}/deleteData`,
              payload: {
                list: aa,
                eventCreateUser: currentUnitName,
                eventStartTime: moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00'),
                eventEndTime: moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59'),
                current,
                pageSize,
              },
            });
          } else {
            dispatch({
              type: `${this.modularName}/deleteData`,
              payload: {
                list: aa,
                eventCreateUser: currentUnitName,
                current,
                pageSize,
              },
            });
          }
        });
      },
      onCancel() {},
    });
  };

  onOk = () => {
    const { dispatch, form, global, modular } = this.props;
    const { query, currentUnitName } = this.state;
    const { currentUnit } = global;
    const { editData = {}, current, pageSize } = modular;

    form.validateFields({ force: true }, (err, values) => {
      if (values.isEvent == '1') {
        // form.setFieldsValue({ eventType: ["社会安全","刑事案件"], eventAddress: ' ', eventTheTime: moment(), eventCriminal: moment(), eventSiuation: ' ' });
      }
      // else if(values.isEvent == "0"){
      //   form.setFieldsValue({ eventType: "", eventAddress: "", eventTheTime: moment(), eventCriminal: moment(), eventSiuation: "" });
      // }
      if (!err) {
        const { filterTime, ...data } = values;
        const { eventType, eventCriminal, eventCreateTime, eventTheTime, reportTime } = data;

        if (filterTime) {
          if (editData.id) {
            dispatch({
              type: `${this.modularName}/saveOrUpdateData`,
              payload: {
                data: {
                  id: editData.id,
                  ...data,
                  eventType: eventType[0] + '/' + eventType[1],
                  eventCriminal: eventCriminal.format('YYYY-MM-DD HH:mm'),
                  eventCreateTime: eventCreateTime.format('YYYY-MM-DD HH:mm'),
                  eventTheTime: eventTheTime.format('YYYY-MM-DD HH:mm'),
                  reportTime: reportTime.format('YYYY-MM-DD'),
                },
                current,
                pageSize,
                eventCreateUser: currentUnitName,
                eventStartTime: moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00'),
                eventEndTime: moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59'),
              },
            });
          } else {
            dispatch({
              type: `${this.modularName}/saveOrUpdateData`,
              payload: {
                data: {
                  // id: 0,
                  ...data,
                  eventType: eventType[0] + '/' + eventType[1],
                  eventCriminal: eventCriminal.format('YYYY-MM-DD HH:mm'),
                  eventCreateTime: eventCreateTime.format('YYYY-MM-DD HH:mm'),
                  eventTheTime: eventTheTime.format('YYYY-MM-DD HH:mm'),
                  reportTime: reportTime.format('YYYY-MM-DD'),
                },
                current,
                pageSize,
                eventCreateUser: currentUnitName,
                eventStartTime: moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00'),
                eventEndTime: moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59'),
              },
            });
          }
        } else {
          if (editData.id) {
            dispatch({
              type: `${this.modularName}/saveOrUpdateData`,
              payload: {
                data: {
                  id: editData.id,
                  ...data,
                  eventType: eventType[0] + '/' + eventType[1],
                  eventCriminal: eventCriminal.format('YYYY-MM-DD HH:mm'),
                  eventCreateTime: eventCreateTime.format('YYYY-MM-DD HH:mm'),
                  eventTheTime: eventTheTime.format('YYYY-MM-DD HH:mm'),
                  reportTime: reportTime.format('YYYY-MM-DD'),
                },
                current,
                pageSize,
                eventCreateUser: currentUnitName,
              },
            });
          } else {
            dispatch({
              type: `${this.modularName}/saveOrUpdateData`,
              payload: {
                data: {
                  id: 0,
                  ...data,
                  eventType: eventType[0] + '/' + eventType[1],
                  eventCriminal: eventCriminal.format('YYYY-MM-DD HH:mm'),
                  eventCreateTime: eventCreateTime.format('YYYY-MM-DD HH:mm'),
                  eventTheTime: eventTheTime.format('YYYY-MM-DD HH:mm'),
                  reportTime: reportTime.format('YYYY-MM-DD'),
                },
                current,
                pageSize,
                eventCreateUser: currentUnitName,
              },
            });
          }
        }
      }
    });
  };

  onOkExport = () => {
    const { dispatch, form, modular } = this.props;
    const { selectedEvents, visibleExport } = modular;
    const { selectedRows } = this.state;

    form.validateFields({ force: true }, (err, values) => {
      if (err) {
      } else {
        const { qishu, timeType } = values;
        let timeStart = moment(qishu[0]).format('YYYY-MM-DD HH:mm');
        let timeEnd = moment(qishu[1]).format('YYYY-MM-DD HH:mm');
        dispatch({
          type: `${this.modularName}/downloadData`,
          payload: {
            startTime: timeStart,
            endTime: timeEnd,
            type: timeType,
          },
        });
      }
    });
  };

  //重置
  clearQueryDatas = () => {
    this.setState({ current: 1 });
    this.props.form.resetFields();
  };

  //种类选择
  onChangeSelectType = value => {
    this.setState({ selectType: value, selectStatement: 1, checkedList: [] });
    this.props.dispatch({
      type: `${this.modularName}/callType`,
      payload: {
        scene: value,
      },
    });
    this.props.dispatch({
      type: `${this.modularName}/callStatement`,
      payload: {
        sheechArt: value,
      },
    });
  };

  //催告按钮
  onShowNotice = noticeType => {
    this.setState({ noticeVisible: true, noticeType, checkedList: [] });

    if (noticeType == 0) {
      this.setState({ selectType: '防台防汛' });
      this.props.dispatch({
        type: `${this.modularName}/callSelect`,
        payload: {},
      });
    }

    if (noticeType == 1) {
      this.props.dispatch({
        type: `unit/queryData`,
        payload: {
          state: DEFAULT_VALID_STATE,
          current: 1,
          pageSize: 10000,
          callback: (data = []) => {
            if (!data.length) return;
            let plainOptions = data.map(item => item.unit_name);
            this.setState({ plainOptions });
          },
        },
      });
    }
  };
  // eslint-disable-next-line lines-between-class-members
  noticeOk = () => {
    const { selectType, selectStatement, checkedList, noticeType } = this.state;
    console.log(selectType, selectStatement, checkedList);

    if (noticeType === 0) {
      this.props.dispatch({
        type: `${this.modularName}/noticeData`,
        payload: {
          noticeType,
          body: {
            jdmcs: checkedList,
            type: selectType,
            level: selectStatement,
          },
        },
      });
      this.setState({ noticeVisible: false });
    }

    if (noticeType === 1) {
      this.props.dispatch({
        type: `${this.modularName}/noticeData`,
        payload: {
          noticeType,
          body: this.state.checkedList,
        },
      });
      this.setState({ noticeVisible: false });
    }
  };

  noticeCancel = () => {
    this.setState({ noticeVisible: false });
  };

  onCheckboxChange = checkedList => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < this.state.plainOptions.length,
      checkAll: checkedList.length === this.state.plainOptions.length,
    });
  };

  onCheckAllChange = e => {
    this.setState({
      checkedList: e.target.checked ? this.state.plainOptions : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };

  render() {
    const { selectedRows = [], noticeType, selectStatement } = this.state;
    const { dispatch, loading, form, global, modular } = this.props;
    const { getFieldDecorator } = form;
    const { currentUnit = {} } = global;
    const {
      callSelectData,
      callTypeData,
      callStatementData,
      data = [],
      current = 1,
      pageSize = DEFAULT_PAGE_SIZE,
      total = 0,
      rowKey,
      visible,
      editData = {},
      visibleExport = false,
    } = modular;
    const columns = [
      {
        title: '标题',
        dataIndex: 'eventTitle',
        ellipsis: true,
        width: 320,
      },
      {
        title: '值班部门',
        dataIndex: 'eventSubordinateUnit',
        ellipsis: true,
        width: 320,
      },
      {
        title: '街道',
        dataIndex: 'streetName',
        ellipsis: true,
        width: 320,
      },
      {
        title: '内容',
        dataIndex: 'eventBrief',
        ellipsis: true,
        width: 320,
      },
      {
        title: '发生地点',
        dataIndex: 'eventAddress',
        ellipsis: true,
        width: 120,
      },
      {
        title: '应对情况',
        dataIndex: 'eventSiuation',
        ellipsis: true,
        width: 320,
      },
      {
        title: '创建时间',
        dataIndex: 'eventCreateTime',
        ellipsis: true,
        width: 200,
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div className={styles.common_span_group}>
              <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
              <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>删除</span>
            </div>
          );
        }
      }
    ];
    return (
      <Layout className={styles.basic_layout_wrapper}>
        <div className={styles.title}>
          当前单位: <span style={{ color: 'rgb(27, 139, 236)' }}>{currentUnit.unit_name}</span>
        </div>
        <div className={styles.conditions_wrapper}>
          {CONDITIONS.map(item => {
            if (item.type === 'dateRange') {
              return (
                <div key={item.field} className={styles.item_wrapper}>
                  <div>{item.label}</div>
                  <div>
                    {getFieldDecorator(
                      'filterTime',
                      {},
                    )(<RangePicker style={{ width: 300 }} allowClear={false} />)}
                  </div>
                </div>
              );
            } else if (item.type === 'select') {
              return (
                <div key={item.field} className={styles.item_wrapper}>
                  <div>{item.label}</div>
                  <div>
                    {getFieldDecorator(
                      'filterType',
                      {},
                    )(
                      <Select placeholder={item.placeholder} style={{ width: 180 }}>
                        <Option value="1" key="zbgz">
                          值班工作
                        </Option>
                        <Option value="2" key="ylyd">
                          舆论应对
                        </Option>
                        <Option value="3" key="jrgz">
                          舆情选摘
                        </Option>
                        <Option value="4" key="jrgz">
                          今日关注
                        </Option>
                      </Select>,
                    )}
                  </div>
                </div>
              );
            }
          })}
          <div className={styles.item_wrapper}>
            <Button
              icon="redo"
              style={{ marginRight: 16, minWidth: 90, marginBottom: 16 }}
              onClick={this.clearQueryDatas}
            >
              重置
            </Button>
            <Button
              type="primary"
              icon="search"
              style={{ minWidth: 90, marginBottom: 16 }}
              onClick={this.queryList.bind(this)}
            >
              查询
            </Button>
          </div>
          <div className={styles.item_wrapper} style={{ float: 'right', marginRight: 0 }}>
            <Button
              type="danger"
              icon="customer-service"
              onClick={() => this.onShowNotice(0)}
              style={{ marginRight: 16 }}
            >
              会议话机点名
            </Button>
            <Button
              type="danger"
              icon="customer-service"
              onClick={() => this.onShowNotice(1)}
              style={{ marginRight: 16 }}
            >
              催告
            </Button>
            <Button
              icon="cloud-download"
              className={styles.common_btn_type_orange}
              onClick={this.exportBtnClick}
            >
              导出
            </Button>
          </div>
        </div>
        <Content className={styles.conditions_wrapper} style={{ margin: 0 }}>
          <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
            <div>
              <Button
                icon="plus"
                type="primary"
                style={{ width: 110, marginRight: 16, marginBottom: 16 }}
                onClick={this.appendBtnClick}
              >
                新增
              </Button>
            </div>
            <Content className={styles.common_table_wrapper}>
              <Table
                columns={columns}
                dataSource={data}
                loading={
                  !!loading.effects[`${this.modularName}/queryData`] ||
                  !!loading.effects[`${this.modularName}/deleteData`]
                }
                pagination={false}
                rowKey={rowKey}
                rowSelection={{
                  onChange: (selectedRowKeys, rows) => {
                    this.setState({
                      chooseArray: selectedRowKeys,
                      selectedRows: [
                        ...selectedRows.filter(
                          item =>
                            selectedRowKeys.includes(item.id) &&
                            !rows.map(row => row.id).includes(item.id),
                        ),
                        ...rows,
                      ],
                    });
                  },
                }}
                scroll={{ x: true }}
              />
            </Content>
            <div style={{ margin: '16px 0' }}>
              <Pagination
                current={current}
                pageSize={pageSize}
                total={total}
                showQuickJumper
                showSizeChanger
                showTotal={(total, range) => `共有 ${total} 条数据`}
                onChange={this.onChange}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          </Layout>
        </Content>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={560}
          onOk={this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined,
                editData: {},
              },
            });
          }}
        >
          <Edit
            dispatch={dispatch}
            form={form}
            modularName={this.modularName}
            areas={modular.areas}
            data={editData}
            disabled={visible === '查看用户'}
            eventCreateUser={currentUnit.unit_name}
          />
        </Modal>
        {/* 导出 */}
        <Modal
          className={styles.exportcss}
          centered
          destroyOnClose
          maskClosable={false}
          title="数据导出"
          visible={!!visibleExport}
          wrapClassName={styles.common_modal_wrapper}
          width={600}
          onOk={this.onOkExport}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visibleExport: undefined,
              },
            });
          }}
        >
          <Export
            dispatch={dispatch}
            form={form}
            modularName={this.modularName}
            areas={modular.areas}
            data={editData}
            disabled={visible === '查看用户'}
          />
        </Modal>
        {/* 催告 */}
        <Modal
          title="催告列表"
          visible={this.state.noticeVisible}
          onOk={this.noticeOk}
          onCancel={this.noticeCancel}
        >
          <div className={styles.call_select_top}>
            <div>
              <Checkbox
                indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={this.state.checkAll}
              >
                全选
              </Checkbox>
            </div>
            <div className={styles.call_select}>
              {callSelectData && noticeType === 0 && (
                <Select
                  defaultValue={this.state.selectType}
                  onChange={this.onChangeSelectType}
                  // style={{ width: "40%" }}
                >
                  {callSelectData.map(item => {
                    return (
                      <Option value={item.scene} key={item.scene}>
                        {item.scene}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </div>
          </div>
          <br />
          <CheckboxGroup
            options={this.state.plainOptions}
            value={this.state.checkedList}
            onChange={this.onCheckboxChange}
          />
          <Form.Item label="话术" style={{ marginTop: 20 }}>
            {noticeType === 0 && (
              <Select
                defaultValue={1}
                style={{ width: '100%' }}
                value={this.state.selectStatement}
                onChange={value => this.setState({ selectStatement: value })}
              >
                {callStatementData ? (
                  callStatementData.map(item => {
                    return (
                      <Option value={item.id} key={item.id}>
                        {item.SpeechArt}
                      </Option>
                    );
                  })
                ) : (
                  <Option value={1}>{'loading...'}</Option>
                )}
              </Select>
            )}

            {noticeType === 1 && (
              <Select defaultValue="1" style={{ width: '100%' }}>
                <Option value="1" key="zbgz">
                  您好，您单位还有值守保障信息未按要求上报至区总值班室，请及时做好相关信息报送工作，请问您听清楚了吗？
                </Option>
              </Select>
            )}
          </Form.Item>
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, global, dutyNotesNew, unit }) => ({
  loading,
  global,
  modular: dutyNotesNew,
  unit,
}))(Form.create()(Index));
